package com.bit.trans.controller;

import com.bit.trans.service.LogService;
import com.bit.trans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
//import org.springframework.transaction.TransactionDefinition;
//import org.springframework.transaction.TransactionStatus;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RequestMapping("/user2")
@RestController
public class UserController2 {
    @Autowired
    private UserService userService;
    @Autowired
    private LogService logService;

    @Transactional
    @RequestMapping("/registry")
    public String registry(String name,String password){

        //用户注册；
        Integer result= userService.registryUser(name,password);
        log.info("用户注册成功，影响行数："+result);
        //进行手动回滚事务的设置；
        //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return "注册成功";
    }
//    @Transactional(roolbackFor={IOException.class,RuntimeException.class})
//    @RequestMapping("/r2")
//    public String r2(String name,String password)throws  IOException{
//        //用户注册；
//        Integer result= userService.registryUser(name,password);
//        log.info("用户注册成功，影响的行数是："+result);
//        if(true){
//            throw  new IOException();
//        }
//        return "注册成功";
//    }


    //进行事务的隔离级别的设置；
@Transactional(isolation = Isolation.DEFAULT)
@RequestMapping("/r3")
public String r3(String name,String password)throws  IOException{
    //用户注册；
    Integer result= userService.registryUser(name,password);
    log.info("用户注册成功，影响的行数是："+result);
    if(true){
        throw  new IOException();
    }
    return "注册成功";
}
//进行事务的转播机制的相关定义；
@Transactional(propagation = Propagation.REQUIRES_NEW)
@RequestMapping("/r4")
public String r4(String name,String password){
    //用户注册；
    Integer result= userService.registryUser(name,password);
    log.info("用户注册成功，影响的行数是："+result);
    return "注册成功";
}
//进行事务转播机制的相关练习；
    @Transactional
    @RequestMapping("/r5")
    public String r5(String name,String password){
        //用户注册；
        Integer result= userService.registryUser(name,password);
        log.info("用户注册成功，影响的行数是："+result);
        Integer logResult=logService.insertLog(name,"用户登录");
        log.info("日志记录成功，影响的行数："+logResult);
        return "注册成功";
    }

}
